package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("loginServlet")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
        String username =  req.getParameter("username");
        String password =  req.getParameter("password");
        String checkCode =  req.getParameter("checkCode");
        HttpSession session = req.getSession();
        String checkCode_session =(String) session.getAttribute("checkCode_session");
        session.removeAttribute("checkCode_session");
        if (checkCode_session!=null && checkCode_session.equalsIgnoreCase(checkCode)){
            if ("gao".equals(username) && "123".equals(password)){
                //登陆成功 存储信息
                session.setAttribute("user",username);
                resp.sendRedirect(req.getContextPath()+"/success.jsp");
            }else {
                req.setAttribute("login_error","用户名或密码错误");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }else{
            req.setAttribute("cc_error","验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
